package com.suoluo.zenadmin.controllers.api;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

import javax.annotation.Resource;

import net.paoding.rose.web.ControllerInterceptorAdapter;
import net.paoding.rose.web.Invocation;

import com.suoluo.zenadmin.common.APPConstants;
import com.suoluo.zenadmin.common.encrypt.EncryptUtil;
import com.suoluo.zenadmin.service.app.AppService;
import com.suoluo.zenadmin.vo.app.AppInstanceVO;

public class APIInterceptor extends ControllerInterceptorAdapter{
	@Resource(name="appService")
	private AppService appService;
	
	@Override
	protected Object before(Invocation inv) throws Exception {
		

		String secret = inv.getParameter("secret");
		String time = inv.getParameter("time");
		int dataId = 0;
		int type = 0;
		String act = inv.getRequestPath().getModulePath();
		if(act.indexOf("dest") != -1) {
			type = APPConstants.DEST;
			dataId = Integer.parseInt(inv.getParameter("destId"));
		}
		else if(act.indexOf("hotel") != -1) {
			type = APPConstants.HOTEL;
			dataId = Integer.parseInt(inv.getParameter("hotelId"));
		}
		
		//1.获取目的地库里保存的token
		AppInstanceVO appVO  = appService.findTokenByTypeAndDataId(type,dataId);
		if(appVO == null)
		{
			return "@json:{resultCode:1003,resultMsg:该应用信息不存在！}";
		}
		StringBuilder temp = new StringBuilder(appVO.getToken());
		temp.append(time);
		//2.验证secret
		String tempSecret = EncryptUtil.md5(temp.toString());
		if(tempSecret.equals(secret))
		{
			return true;
		}
		return "@json:{resultCode:1001,resultMsg:应用token错误，secret是md5(token+time)加密后的结果！}";
		
	}

	public AppService getAppService() {
		return appService;
	}

	public void setAppService(AppService appService) {
		this.appService = appService;
	}

}
